package mianyang.zhangsan.com.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import mianyang.zhangsan.com.pojo.LoginUser;
import mianyang.zhangsan.com.pojo.User;
import mianyang.zhangsan.com.service.UserService;
import mianyang.zhangsan.com.utils.ExcelUtils;
import mianyang.zhangsan.com.utils.Upload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 前台登录请求
     * @param loginUser
     * @param model
     */
    @RequestMapping("/frontLogin")
    public void login(@RequestBody LoginUser loginUser,
                      Model model){
        User user = userService.queryUserInfo(loginUser.getUsername());
        if (user != null){
            if (user.getPassword().equals(loginUser.getPassword())) {
                model.addAttribute("message", "登录成功");
            }
        }

    }

    /**
     * 跳转到用户添加页面
     * @return
     */
    @RequestMapping(value="/toFrontAdd")
    public String toFrontAdd(){
        return "userInfo/userInfo_add";
    }

    /**
     * 前端添加用户
     * @param user
     */
    @RequestMapping("/frontAdd")
    public void frontAdd(@RequestBody User user){
        System.out.println(user);
    }

    /**
     * 前端查询用户信息
     * @param pageNo
     * @param model
     * @return
     */
    @RequestMapping("frontList")
    public String frontList(@RequestParam("pageNo")int pageNo, Model model){
        Page<User> userPage = userService.queryUserInfoList(pageNo);
        model.addAttribute("users", userPage.getRecords());
        model.addAttribute("pages", userPage.getPages());
        userPage.setRecords(null);
        model.addAttribute("page", userPage);
        return "userInfo/userInfo_front_result";
    }

    /**
     * 展示用户详细信息
     * @param username
     * @param model
     * @return
     */
    @RequestMapping("/frontShow")
    public String frontShow(@RequestParam("username")String username, Model model){
        User user = userService.queryUserInfo(username);
        model.addAttribute("user", user);
        return "userInfo/userInfo_frontShow";
    }

    /**
     * 跳转到用户添加页面
     * @return
     */
    @RequestMapping("/toAdd")
    public String toAdd(){
        return "userInfo/userInfo_add";
    }

    /**
     * 后台添加用户信息
     * @param request
     * @param user
     * @return
     * @throws IOException
     */
    @RequestMapping("/add")
    @ResponseBody
    public String add(HttpServletRequest request, User user) throws IOException {
        //判断用户信息是否符合
        User temp = userService.queryUserInfo(user.getUsername());
        if (temp != null){
            return "{\"success\": \"false\",    \"message\": \"用户名存在\"}";
        }
        try {
            user.setUserPhoto(Upload.handlePhotoUpload(request, "userPhotoFile"));
        } catch (IOException e) {
            e.printStackTrace();
            return "{\"success\": \"false\",    \"message\": \"图片格式不正确\"}";
        }
//        System.out.println(user);
        userService.addUser(user);
        return  "{\"success\" : \"true\"}";
    }

    /**
     * 字符串类型的user
     * @param user
     * @param file
     */
    @RequestMapping("/upload")
    public void testUpload(String user, MultipartFile file){
        System.out.println(user);
        User zhangsan = JSON.parseObject(user, User.class);
        System.out.println(zhangsan);
        System.out.println(file);
    }

    @RequestMapping("/query")
    public String userQuery(){
        return "userInfo/userInfo_query_result";
    }

    /**
     * 后台用户信息查询
     * @param user 查询的条件
     * @param page 当前的页码
     * @param rows 当前页显示的消息条数
     */
    @RequestMapping(value = "/list", produces = "application/json;charset=utf-8")
    @ResponseBody
    public String list(User user, Integer page, Integer rows){
        System.out.println(user);
        Page<User> userPage = userService.queryPageByWrapper(page, rows, user);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("total", userPage.getPages());
        JSONArray jsonArray = new JSONArray();
        for(User item:userPage.getRecords()){
            Object o = JSON.toJSON(item);
            jsonArray.add(o);
        }
        jsonObject.put("rows", jsonArray);
        System.out.println(jsonObject.toJSONString());
        System.out.println(jsonObject.toString());
        return jsonObject.toString();
    }

    /**
     * 删除一个用户
     * @param username
     * @param model
     * @return
     */
    @RequestMapping("/delete")
    public String deleteOne(@RequestParam("username") String username, Model model){
        try {
            userService.deleteUser(username);
            model.addAttribute("message", "用户删除成功");
            return "message";
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("error", "用户删除失败");
            return "error";
        }
    }

    /**
     * 删除多个用户
     * @param usernames
     */
    @RequestMapping("/deletes")
    public void deleteUsers(@RequestParam("usernames")String usernames){
        userService.deleteUsers(usernames);
    }

    /**
     * 后台查询用户数据
     * @return
     */
    @RequestMapping(value = "/listAll", produces = "application/json;charset=utf-8")
    @ResponseBody
    public String queryList(){
       List<User> users = userService.queryList();
       JSONArray response = new JSONArray();
       for (User user : users){
           JSONObject jsonObject = new JSONObject();
           jsonObject.put("user_name", user.getUsername());
           jsonObject.put("name", user.getName());
           response.add(jsonObject);
       }
       return response.toString();
    }

    /**
     * 后台导出查询数据
     * @param user
     * @param response
     */
    @RequestMapping("/outToExcel")
    public void toExcel(User user, HttpServletResponse response){
        List<User> users = userService.queryListByWrapper(user);
        String[] headers = { "用户名","姓名","性别","用户照片","出生日期","身份证号","联系电话","邮箱","注册时间"};
        String title = "用户表";
        List<String[]> contents = new ArrayList<>();
        for (User item:users){
            contents.add(new String[]{item.getUsername(),item.getName(),item.getGender(),item.getUserPhoto(),item.getBirthday(),item.getCardNumber(),item.getTelephone(),item.getEmail(),item.getRegTime()});
        }
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            response.setHeader("Content-disposition","attachment; filename="+"userInfo.xls");//filename是下载的xls的名，建议最好用英文
            response.setContentType("application/msexcel;charset=UTF-8");//设置类型
            response.setHeader("Pragma","No-cache");//设置头
            response.setHeader("Cache-Control","no-cache");//设置头
            response.setDateHeader("Expires", 0);//设置日期头
            ExcelUtils.exportExcel(title, headers, contents, out);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (out != null){
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
